<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Upload File</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
</head>
<body>
    <div id="app">
        <input type="file" @change="handleFileChange" accept=".txt,.zip">
        <button @click="uploadFile">上传文件</button>
        <p v-if="fileUrl">{{ fileUrl }}</p>
    </div>

  <script>
    new Vue({
      el: '#app',
      data: {
        selectedFile: null,
        fileUrl: ''
      },
      methods: {
        handleFileChange(event) {
          this.selectedFile = event.target.files[0];
        },
        async uploadFile() {
          if (!this.selectedFile) {
            alert('请选择要上传的文件');
            return;
          }
          
          const formData = new FormData();
          formData.append('file', this.selectedFile);

          // 构建又拍云的签名逻辑，这里仅为示例，实际应用中需要替换为真实的签名逻辑
          const bucket = 'wey-suv';
          const operator = 'ouwen000';
          const password = 'd0ZkZeg8ptFjMzpdBkXgV4ccv4jdMzAi';

          const fileName = '1.txt';
          const savePath = '/zip/';

          const date = new Date().toUTCString();
          const policy = {
            "bucket": bucket,
            "save-key": savePath + fileName,
            "expiration": Math.round(new Date().getTime() / 1000) + 3600, // 有效期1小时
          };
          const policyBase64 = btoa(JSON.stringify(policy));

          const stringToSign = ['POST', '/' + policy.bucket, policyBase64].join('&');

          const url = `https://ad.wenfree.cn/?data=${encodeURIComponent(stringToSign)}`;

          console.log('url:', url);

        fetch(url)
            .then(response => response.json())
            .then(data => {
                const signature = data.data; // 假设返回的签名字段为 signature
                console.log(signature)
                // 在这里可以继续使用获取到的签名进行后续操作
                handleSignature();
            })
            .catch(error => {
                console.error('获取签名失败', error);
            });

        //   console.log('signature:', sign);

              
          console.log('stringToSign:', stringToSign);
          
          formData.append('policy', policyBase64);

          console.log('Signature:', signature);
          console.log('policy:', policyBase64);

          formData.append('Authorization', `UPYUN ${operator}:${signature}`);
          formData.append('Date', date);

          try {
            const res = await fetch(`https://v0.api.upyun.com/${bucket}/`, {
              method: 'POST',
              body: formData
            });

            if (res.ok) {
              const responseData = await res.json();
              this.fileUrl = responseData.url;
            } else {
              console.error('上传失败');
            }
          } catch (error) {
            console.error('上传失败：', error);
          }


        }
      }
    });
  </script>
</body>
</html>